package cn.com.czpb.client.module.baoliao;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.utils.ImageUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;

import java.io.File;

import butterknife.BindView;

/**
 * Created by 猪猪侠 on 2017/10/30.
 */

public class BaoliaoActivity extends MToolBarActivity {
    public static final int TYPE_0 =0;//我要爆料
    public static final int TYPE_1 =1;//发起爆料
    public static final String TAG = "BaoliaoActivity";
    private LoginQuitBR br;
    @BindView(R.id.webview_id)
    WebView webviewId;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;

    private final static int FILECHOOSER_RESULTCODE = 1;

    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private int RESULT_OK =-1;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_baoliao;
    }

    @Override
    public void initView() {
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        Intent intent = getIntent();
int type = intent.getIntExtra("type",0);
        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(TAG);
        registerReceiver(br, filter);

        WebSettings settings = webviewId.getSettings();
        settings.setSavePassword(false);
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setUseWideViewPort(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setDomStorageEnabled(true);

        settings.setAllowFileAccess(true);
        if (TYPE_0==type){
            if (spu.getUser() == null) {
                webviewId.loadUrl(InterfaceJsonfile.BAOLIAOURL);
            } else {
                webviewId.loadUrl(InterfaceJsonfile.BAOLIAOURL + spu.getUser().getUid());
            }
        }else{
            if (spu.getUser() == null) {
                PageCtrl.start2LoginActivity(BaoliaoActivity.this);
//                webviewId.loadUrl(InterfaceJsonfile.MYBAOLIAOURL);
            } else {
                webviewId.loadUrl(InterfaceJsonfile.MYBAOLIAOURL + spu.getUser().getUid());
            }
        }

        webviewId.setWebViewClient(new WebViewClient() {
            //            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.i("url-->"+url);
                if (url.contains("g=Baoliao&m=Baoliao&a=add")) {
                    if (spu.getUser() == null) {
                        PageCtrl.start2LoginActivity(BaoliaoActivity.this);
                    } else {
                        view.loadUrl(url);
                    }
                }
                return super.shouldOverrideUrlLoading(view,url);
            }


        });
        webviewId.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && webviewId.canGoBack()) {
                        //表示按返回键 时的操作
                        webviewId.goBack(); //后退
                        return true; //已处理 ...
                    }
                }
                return false;
            }
        });
        webviewId.setWebChromeClient(new WebChromeClient() {
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                activity.startActivityForResult(
                        Intent.createChooser(i, "File Chooser"),
                        FILECHOOSER_RESULTCODE);

            }
            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg,
                                        String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                activity.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
            }


            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                activity.startActivityForResult(
                        Intent.createChooser(i, "File Chooser"),
                        FILECHOOSER_RESULTCODE);
            }
            // For Lollipop 5.0+ Devices
            public boolean onShowFileChooser(WebView mWebView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                LogUtils.i("onShowFileChooser-->5");
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

    }
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent data) {
        if (data != null) {
            if(requestCode==FILECHOOSER_RESULTCODE)
            {
                if (null == mUploadMessage && null == uploadMessageAboveL) return;
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                Uri originalUri = data.getData();
                LogUtils.i("uri-->1"+originalUri);
                if (originalUri != null) {
                    String logopath = ImageUtils.getPath(activity, originalUri);
                    Uri uri = Uri.fromFile(new File(logopath));
                    if (uploadMessageAboveL != null) {
                        onActivityResultAboveL(requestCode, resultCode, data);
                    }
                    else  if (mUploadMessage != null) {
//                        mUploadMessage.onReceiveValue(originalUri);
                        mUploadMessage.onReceiveValue(uri);
                        mUploadMessage = null;
                    }
                }
            }
        }else{
            LogUtils.i("data-->null");
        }
        super.onActivityResult(requestCode, resultCode, data);}

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || uploadMessageAboveL == null) {
            return;
        }

        Uri[] results = null;
        if (resultCode == this.RESULT_OK) {
            LogUtils.i("data--->"+data);
            if (data == null) {

            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                LogUtils.i("clipData--->"+clipData);
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
        return;
    }

    @Override
    public void onBackPressed() {
        if (webviewId.canGoBack()){
            webviewId.goBack();
        }else{
            finish();
        }

        super.onBackPressed();
    }
    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtils.e("Unlogin");
            if (spu.getUser() != null) {
                webviewId.loadUrl(InterfaceJsonfile.BAOLIAOURL + spu.getUser().getUid());
            } else {
                webviewId.loadUrl(InterfaceJsonfile.BAOLIAOURL);
            }
        }
    }
}
